<template>
  <div>
     <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片列表内容区 -->
    <el-card class="box-card">
      <!-- 头部搜索操作区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getCateList">
            <el-button slot="append" icon="el-icon-search" @click="getCateList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-plus" @click="showAddCateDialog">新增分类</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <tree-table class="treeTable" :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index border>
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color:lightgreen;"></i>
          <i class="el-icon-error" v-else style="color:red;"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 新增dialog -->
    <el-dialog
      title="新增分类信息"
      :visible.sync="addCateVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="addFormClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader 
          v-model="selectedKeys" 
          :options="parentCateList"
          :props="catCasProps"
          @change="catCasChange" clearable change-on-select filterable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改dialog -->
    <el-dialog
      title="修改分类信息"
      :visible.sync="editCateVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="editFormClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 2,
      },
      cateList: [],
      total: 0,
      addCateVisible: false,
      editCateVisible: false,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        },
      ],
      addForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      editForm: {},
      addFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      editFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      parentCateList: [],
      catCasProps:{
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: []
    }
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败");
      this.cateList = res.data;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    showAddCateDialog(){
      this.getParentCateList();
      this.addCateVisible = true;
    },
    addFormClosed() {
      this.addForm.cat_pid = 0;
      this.addForm.cat_level = 0;
      this.selectedKeys = [];
      this.$refs.addFormRef.resetFields();
    },
    addCate() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        //向服务器发起请求
        const { data: res } = await this.$http.post("categories", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("分类新增失败");
        this.getCateList();
        this.$message.success("分类新增成功");
        this.addCateVisible = false;
      });
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories",{ params: {type: 2 }});
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败");
      this.parentCateList = res.data;
    },
    catCasChange() {
      if(this.selectedKeys.length > 0){
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length -1];
        this.addForm.cat_level = this.selectedKeys.length;
      }else{
        this.addForm.cat_pid = 0;
        this.addForm.cat_level = 0;
      }
    },
    async showEditCateDialog(cateId) {
      const { data: res } = await this.$http.get("categories/" + cateId);
      if (res.meta.status !== 200)
        return this.$message.error("分类信息获取失败");
      this.editForm = res.data;
      this.editCateVisible = true;
    },
    async editCate() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        //向服务器发起请求
        const { data: res } = await this.$http.put("categories/" + this.editForm.cat_id, {cat_name:this.editForm.cat_name });
        if (res.meta.status !== 200) return this.$message.error("分类修改失败");
        this.getCateList();
        this.$message.success("分类修改成功");
        this.editCateVisible = false;
      });
    },
    editFormClosed(){
      this.editForm = {};
      this.$refs.editFormRef.resetFields();
    },
    async deleteCate(cateId) {
      const result = await this.$confirm("确认删除此分类吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(error => error);
      if(result !== "confirm") return this.$message.info("已取消删除");
      const {data: res} = await await this.$http.delete('categories/' + cateId);
      if(res.meta.status !== 200) return this.$message.error("分类删除失败");
      this.$message.success("分类删除成功");
      this.getCateList();
    }
  }
}
</script>

<style lang="less" scoped>
  .treeTable{
    margin-top: 15px;
  }
  .el-cascader{
    width: 100%;
  }
</style>